package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import svc.LoginSvc;

/**
 * Servlet implementation class Register
 */
//@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private LoginSvc svc = new LoginSvc();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		//HttpSession session = request.getSession();
		String name = request.getParameter("name");
	    String email = request.getParameter("email");
	    String password = request.getParameter("password");
	    String rePassword = request.getParameter("repassword");
	    String registerMessage = "";
	    int pageId=0;
	    
	    boolean passwordsMatch = password.equals(rePassword);
	    
	    if(name.length()==0 || email.length()==0 || password.length()==0){
	    	registerMessage = "All fields are mandatory.";
	    }else if(!passwordsMatch){
	    	registerMessage = "Passwords do not match!";
	    }else{
	    	boolean userExists = svc.doesUserExists(email);
	    	if(userExists){
	    		registerMessage = "Email already in use!";
	    	}else{
	    		int isUserRegistered = svc.registerUser(name, email, password);
	    		
	    		if(isUserRegistered!=-1){
	    			registerMessage = "Congratulations! You have been registered as a new user, please login to continue.";
	    		    pageId=1;
	    		}else{
	    			registerMessage = "Sorry, your regestration is not complete due to an unexpected error, kindly try again later.";
	    		}
	    		
	    	}
	    }
	    
	    //session.setAttribute("registerMessage", registerMessage);
	    //response.sendRedirect("../jsp/login.jsp");
	    request.setAttribute("registerMessage", registerMessage);
	    request.setAttribute("pageId", pageId);
	  
	    request.getRequestDispatcher( "/jsp/login.jsp").forward(request,response);
    	
    	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
